<?php
/**
 * Created by PhpStorm.
 * User: xuezhileikaku
 * Email:chengyingbo88@163.com
 * Date: 2024/8/23
 * Time: 下午6:43
 */

namespace App\Event;

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;
class EventDispatcher implements EventDispatcherInterface
{
    private $listenerProvider;

    public function __construct(ListenerProviderInterface $listenerProvider)
    {
        $this->listenerProvider = $listenerProvider;
    }

    /**
     * Dispatches an event to all relevant listeners.
     *
     * @param object $event The event to dispatch.
     * @return object The event that was dispatched.
     */
    public function dispatch(object $event): object
    {
        foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
            $listener($event);

            // Check if event propagation was stopped
            if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
                break;
            }
        }

        return $event;
    }
}
